package com.styytech.dadabao.ui.project;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.RequestParams;
import com.styytech.dadabao.DadaApplication;
import com.styytech.dadabao.R;
import com.styytech.dadabao.api.requestresult.RecommendProductResult;
import com.styytech.dadabao.api.response.AbstractResponseResult;
import com.styytech.dadabao.api.templates.HttpRequest;
import com.styytech.dadabao.base.BaseActivity;
import com.styytech.dadabao.bean.RecommendProduct;
import com.styytech.dadabao.constant.ConstantsServerUrl;
import com.styytech.dadabao.exception.ArgumentsException;
import com.styytech.dadabao.exception.RequestException;
import com.styytech.dadabao.ui.login.LoginActivity;
import com.styytech.dadabao.ui.my.accountset.AuthNameActivity;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.utils.SpUser;
import com.styytech.dadabao.widge.dialog.CalculationDialog;
import com.styytech.dadabao.widge.dialog.EnsureDialog;
import com.styytech.dadabao.widge.dialog.IsInNumDialog;
import com.styytech.dadabao.widge.progressbar.RoundThread;
import com.styytech.dadabao.widge.progressbar.roundprogressbar.RoundProgressBar;

/**
 * Created by user on 2015/8/17.
 */
@ContentView(R.layout.activity_project_details)
public class ProjectDetailsActivity extends BaseActivity implements View.OnClickListener {
    private String search_id;
    /**
     * 投资人数
     */
    @ViewInject(R.id.tv_people_num)
    private TextView tv_people_num;
    /**
     * 项目规模
     */
    @ViewInject(R.id.tv_pro_scale)
    private TextView tv_pro_scale;
    /**
     * 进度条
     */
    @ViewInject(R.id.roundProgressBar)
    private RoundProgressBar roundProgressBar;
    /**
     * 投资比例
     */
    @ViewInject(R.id.tv_pro_progress)
    private TextView tv_pro_progress;
    /**
     * 年化收益
     */
    @ViewInject(R.id.tv_pro_profit)
    private TextView tv_pro_profit;
    /**
     * 项目期限
     */
    @ViewInject(R.id.tv_pro_date)
    private TextView tv_pro_date;
    /**
     * 项目名称
     */
    @ViewInject(R.id.tv_pro_name)
    private TextView tv_pro_name;
    /**
     * 项目类型
     */
    @ViewInject(R.id.tv_pro_type)
    private TextView tv_pro_type;
    /**
     * 起投金额
     */
    @ViewInject(R.id.tv_pro_start)
    private TextView tv_pro_start;
    /**
     * 还款方式
     */
    @ViewInject(R.id.tv_pro_method)
    private TextView tv_pro_method;
    /**
     * 更多详情
     */
    @ViewInject(R.id.tv_more_detials)
    private TextView tv_more_detials;
    /**
     * 最下面的布局
     */
    @ViewInject(R.id.rlyt_bottom)
    private RelativeLayout rlyt_bottom;
    /**
     * 收益计算器
     */
    @ViewInject(R.id.ibtn_calculation)
    private ImageButton ibtn_calculation;
    /**
     * 立即投资
     */
    @ViewInject(R.id.tv_pro_buy)
    private TextView tv_pro_buy;
    /**
     * 主体布局
     */
    @ViewInject(R.id.llyt_main)
    private LinearLayout llyt_main;
    //年化收益和时间
    String proportion, date;
    //项目规模
    double totalNum;
    int isFirst;
    RecommendProduct recommendProduct = null;


    EnsureDialog cardDialog;
    IsInNumDialog isInNumDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        search_id = bundle.getString("id");
        isFirst = 0;
        initViews();
       /* getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);*/

    }

    @Override
    protected void onResume() {
        super.onResume();
        getProDetials();
    }

    private void initViews() {
        DadaApplication.addActivity(this);
        setTopBar("详情", View.VISIBLE, View.VISIBLE, "返回");

        tv_more_detials.setOnClickListener(this);
        ibtn_calculation.setOnClickListener(this);
        tv_pro_buy.setOnClickListener(this);
        roundProgressBar.setFirst_start(-90);
        roundProgressBar.setTotal_length(360);
    }
    private void getProDetials(){
        //获取详情
        //打开等待框
        if (isFirst == 0) {
            llyt_main.setVisibility(View.GONE);
            setView(View.VISIBLE, View.VISIBLE, View.VISIBLE, View.GONE, "正在获取数据，请稍等...");
            isFirst++;
        }
        String url = ConstantsServerUrl.getProductDetialsUrl();
        RequestParams params = new RequestParams();
        params.put("productId", search_id);

        RecommendProductResult logResult = new RecommendProductResult(responseResult);
        try {
            new HttpRequest(this).doPost(logResult, url, params);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO", "2e:" + e);
            e.printStackTrace();
        }
    }

    protected void reloadBtnOnclick() {
        Log.i("INFO", "reloadBtnOnclick");
        getProDetials();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_more_detials:
                //更多详情
                Intent intentMore = new Intent();
                intentMore.setClass(this, MoreDetailsActivity.class);
                Bundle bundleMore = new Bundle();
                bundleMore.putSerializable("recommendProduct", recommendProduct);
                intentMore.putExtras(bundleMore);
                startActivity(intentMore);
                break;
            case R.id.ibtn_calculation:
                //收益计算器
                CalculationDialog dialog = new CalculationDialog(this, this, date, proportion, totalNum);
                dialog.show();
                break;
            case R.id.tv_pro_buy:
                //立即投资
                if (SpUser.getUserToken(this) == null || SpUser.getUserToken(this).equals("")) {
                    startActivity(new Intent(this, LoginActivity.class));
                }else{
                    //判断是否实名认证
                 if (SpUser.getIdCardVStatus(this)==0){
                        showCardDialog();
                    }else {
                     if (SpUser.getUserType(this)==1){
                         Intent intent = new Intent();
                         intent.setClass(this, InCompanyAmount.class);
                         Bundle bundle = new Bundle();
                         bundle.putString("id", search_id);
                         intent.putExtras(bundle);
                         startActivity(intent);
                     }else{
                         Intent intent = new Intent();
                         intent.setClass(this, InvestmentAmountActivity.class);
                         Bundle bundle = new Bundle();
                         bundle.putString("id", search_id);
                         intent.putExtras(bundle);
                         startActivity(intent);
                     }

                    }
                }

                break;
        }
    }
    //需要完成实名认证
    private void showCardDialog(){
        cardDialog = new EnsureDialog(this, "提示", "投资之前需完成实名认证，是否立即完善？", 1,"确定");
        cardDialog.setEnsureDialogCallback(ensureCardcallback);
        cardDialog.setCanceleDialogCallback(cancelCardgcallback);
        cardDialog.NotCancel(false);
        cardDialog.show();
    }
    /**
     * 设置实名认证dialog需要处理的事情
     */
    EnsureDialog.Dialogcallback ensureCardcallback = new EnsureDialog.Dialogcallback() {
        @Override
        public void dialogdo() {
             //startActivity(new Intent(ProjectDetailsActivity.this, AuthNameActivity.class));
            showIsInDialog();
            cardDialog.dismiss();

        }
    };
    EnsureDialog.Dialogcallback cancelCardgcallback = new EnsureDialog.Dialogcallback() {
        @Override
        public void dialogdo() {
            cardDialog.dismiss();

        }
    };

    private void showIsInDialog(){
        isInNumDialog=new IsInNumDialog(this);
        isInNumDialog.setInCallBack(incallback);
        isInNumDialog.setOutCallback(outcallback);
        isInNumDialog.NotCancel(false);
        isInNumDialog.show();

    }
    IsInNumDialog.Dialogcallback incallback = new IsInNumDialog.Dialogcallback() {
        @Override
        public void dialogdo() {
            Intent intent = new Intent();
            intent.setClass(ProjectDetailsActivity.this, AuthNameActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("type", 1);
            intent.putExtras(bundle);
            startActivity(intent);
            isInNumDialog.dismiss();

        }
    };
    IsInNumDialog.Dialogcallback outcallback = new IsInNumDialog.Dialogcallback() {
        @Override
        public void dialogdo() {
            Intent intent = new Intent();
            intent.setClass(ProjectDetailsActivity.this, AuthNameActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("type", 2);
            intent.putExtras(bundle);
            startActivity(intent);
            isInNumDialog.dismiss();

        }
    };

    private void setUpViews(Object object) {
        recommendProduct = (RecommendProduct) object;

        if (recommendProduct == null) {
            setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "获取详情失败");
            return;
        }

        //投资人数
        if (!recommendProduct.getPeople_num().equals("")) {
            tv_people_num.setText(recommendProduct.getPeople_num()+"人");
        }
        //项目规模
        if (recommendProduct.getTotalCredit() != 0) {
            if(recommendProduct.getTotalCredit()<10000){
                tv_pro_scale.setText((int)recommendProduct.getTotalCredit() + "元");
            }else{
                tv_pro_scale.setText((int)(recommendProduct.getTotalCredit() / 10000 )+ "万元");
            }
        }
        int dueStatus=Integer.parseInt(recommendProduct.getDueStatus());
        int saleStatus=Integer.parseInt(recommendProduct.getSaleStatus());
        if (dueStatus==0){
            tv_pro_progress.setText("已结束");
            tv_pro_buy.setText("已结束");
            rlyt_bottom.setBackgroundColor(getResources().getColor(R.color.detials_people_number));
            tv_pro_buy.setClickable(false);
        }/*else if(saleStatus==0){
            tv_pro_progress.setText("预售");
            tv_pro_buy.setText("预售");
            rlyt_bottom.setBackgroundColor(getResources().getColor(R.color.detials_people_number));
            tv_pro_buy.setClickable(false);
        }*/
        else if(saleStatus==2){
            tv_pro_progress.setText("停售");
            tv_pro_buy.setText("停售");
            rlyt_bottom.setBackgroundColor(getResources().getColor(R.color.detials_people_number));
            tv_pro_buy.setClickable(false);
        }else {
            if (recommendProduct.getTotalCredit() != 0 && recommendProduct.getProgress() != 0) {
                //当前百分比
                int s = (int) (((float) recommendProduct.getProgress() / (float) recommendProduct.getTotalCredit()) * 100);
                String ss=String.format("%.2f", ((float) recommendProduct.getProgress() / (float) recommendProduct.getTotalCredit()) * 100);
                Log.e("asd", "百分比" + s);

                Log.e("sadsd","dueStatus-----------"+dueStatus);
                if (s == 100) {
                    tv_pro_progress.setText("售罄");
                    tv_pro_buy.setText("售罄");
                    rlyt_bottom.setBackgroundColor(getResources().getColor(R.color.detials_people_number));
                    tv_pro_buy.setClickable(false);
                    RoundThread myThread = new RoundThread(s, roundProgressBar);
                    myThread.start();
                } else {
                    rlyt_bottom.setBackgroundColor(Color.parseColor("#242D3C"));
                    tv_pro_buy.setClickable(true);
                    tv_pro_progress.setText(ss + "%");
                    RoundThread myThread = new RoundThread(s, roundProgressBar);
                    myThread.start();
                }
            }else{
                tv_pro_progress.setText("0.00%");
            }
        }

        //年化收益
        if (!recommendProduct.getExpectedReturnRatio().isEmpty()) {
            proportion = recommendProduct.getExpectedReturnRatio();
            double ss=Double.parseDouble(proportion);
            tv_pro_profit.setText(String.format("%.2f", ss));

        }

        if (!recommendProduct.getTimeLimit().equals("")) {
            date = recommendProduct.getTimeLimit();
            tv_pro_date.setText(date + "天");
        }
        //项目名字
        if (!recommendProduct.getProductName().equals("")) {
            tv_pro_name.setText(recommendProduct.getProductName());
        }
        //起投金额
        if (recommendProduct.getStart_money() != 0) {
            tv_pro_start.setText((int)(recommendProduct.getStart_money()) + "元起投");
        }
        //项目类型
        if (!recommendProduct.getProductType().equals("")) {
            tv_pro_type.setText(recommendProduct.getProductType());
        }
        //还款方式
        if (!recommendProduct.getRepaymentMethod().equals("")) {
            tv_pro_method.setText(recommendProduct.getRepaymentMethod());
        }

    }

    /**
     * 获取推荐结果处理
     */
    AbstractResponseResult responseResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            // TODO
            Log.e("asd", "object---" + object);
            llyt_main.setVisibility(View.VISIBLE);
            setView(View.GONE, View.VISIBLE, View.VISIBLE, View.GONE, "正在获取数据，请稍等...");
            setUpViews(object);
        }

        @Override
        public void executeError(String message, int errorCode) {
            CommonUtils.showToastMsg(ProjectDetailsActivity.this, "" + message);
            setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "" + message);
        }

        @Override
        public void HttpError(String message, int errorCode) {
            CommonUtils.showToastMsg(ProjectDetailsActivity.this, "" + message);
            setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "" + message);
        }
    };
}
